package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"useryk/model/redisinit"
	"useryk/pkg"
	"useryk/userrpc/internal/svc"
	"useryk/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendsmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendsmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendsmsLogic {
	return &SendsmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendsmsLogic) Sendsms(in *userrpc.SendsmsRequest) (*userrpc.SendsmsResponse, error) {
	// todo: add your logic here and delete this line

	code := rand.Intn(9000) + 1000

	sms, err := pkg.Sendsms(in.Tel, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}

	redisinit.Rdb.Set("sendsms"+in.Tel+in.Source, code, time.Hour*10)

	return &userrpc.SendsmsResponse{}, nil
}
